package com.yhl.admin;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;

import java.time.Duration;
import java.util.Objects;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;

/**
 * 断言
 * @author yhl
 * @create 2021-06-30 14:48
 */
@DisplayName("JUnit5Test2测试")
public class JUnit5Test2 {

    //简单断言
    @Test
    @DisplayName("simple assertion")
    public void simple() {
        assertEquals(3, 3, "simple math");
        assertNotEquals(3, 1 + 1, "unexpected exist");

        assertNotSame(new Object(), new Object());
        Object obj = new Object();
        assertSame(obj, obj);

        assertFalse(1 > 2);
        assertTrue(1 < 2);

        assertNull(null);
        assertNotNull(new Object());
    }

    //数组断言
    @Test
    @DisplayName("array")
    public void array(){
        assertArrayEquals(new int[]{1, 2}, new int[]{1, 2});
    }

    //组合断言
    @Test
    @DisplayName("")
    public void all(){
        assertAll(() -> assertEquals(3, 3, "simple math"),
                () -> assertTrue(3 > 1));

        //上面的lambda表达式相当于Executable函数式接口的匿名实现类
//       assertAll("math",
//                new Executable() {
//                    @Override
//                    public void execute() throws Throwable {
//                        assertEquals(3, 3, "simple math");
//                    }
//                },
//                () -> assertTrue(3 > 1));


    }

    //查看抛出的异常是否和预计的相同
    @Test
    @DisplayName("异常测试")
    public void exceptionTest() {
        ArithmeticException exception = assertThrows(
                //扔出断言异常
                ArithmeticException.class, () -> System.out.println(1 % 0));

    }

    @Test
    @DisplayName("超时测试")
    public void timeoutTest() {
        //如果测试方法时间超过1s将会异常
        assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(500));
    }




}

@DisplayName("前置条件")
class AssumptionsTest {
    private final String environment = "DEV";

    @Test
    @DisplayName("simple")
    public void simpleAssume() {
        assumeTrue(Objects.equals(this.environment, "EV"));
        assumeFalse(() -> Objects.equals(this.environment, "PROD"));
    }

    @Test
    @DisplayName("assume then do")
    public void assumeThenDo() {
        assumingThat(
                Objects.equals(this.environment, "DEV"),
                () -> System.out.println("In DEV")
        );
    }
}
